package com.glsc.ngateway.platform.controller.dev;

import com.glsc.ngateway.common.api.common.ex.Result;
import com.glsc.ngateway.common.api.flowable.dto.FlowDoTaskRespDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.platform.domain.FlowFormDevManage;
import com.glsc.ngateway.platform.domain.TestTask;
import com.glsc.ngateway.platform.dto.*;
import com.glsc.ngateway.platform.service.dev.DevManageService;
import com.glsc.ngateway.platform.service.dev.TestTaskService;
import com.glsc.ngateway.platform.utils.RequestTool;
import com.glsc.ngateway.platform.utils.report.ReportUploadContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author guoj
 * @description: 测试管理
 * @date 2024/7/9 16:53
 */
@RestController
@RequestMapping("/testtask")
@Api(value = "TestTaskController", tags = {"测试管理"})
public class TestTaskController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TestTaskService testTaskService;
    @Resource
    private RequestTool requestTool;
    @Resource
    private DevManageService DevManageService;



    @GetMapping ("/getAllDemand")
    @ApiOperation(value = "查询全部未完成（仅限等待上线节点）和未删除需求", notes = "查询全部未完成（仅限等待上线节点）和未删除需求")
    public Result<List<TestTask>> listPage(@RequestParam(required = false) String systemCode) {
        List<FlowFormDevManage> allDemands = DevManageService.queryAllByNODelAndNOCloase(systemCode);
        return Result.successData(allDemands);
    }


    @PostMapping("/page")
    @ApiOperation(value = "测试管理分页查询", notes = "测试管理分页查询")
    public Result<Page<TestTask>> listPage(@RequestBody TestTaskDto testTaskDto, HttpServletRequest request) {
        testTaskDto.setSystemCode(Strings.isNotBlank(testTaskDto.getSystemCode()) ? testTaskDto.getSystemCode() : null);
        String operatorStart = requestTool.getAccountFromRequest();
        Page<TestTask> page = testTaskService.findPage(testTaskDto,request,operatorStart);
        return Result.successData(page);
    }

    /**
     * 流程发起
     * @param  testTaskFormDto 测试用例流程表单
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/createFlow")
    public PlatformResponse<FlowDoTaskRespDto> createFlow(@RequestBody TestTaskFormDto testTaskFormDto) {
        String operatorStart = requestTool.getAccountFromRequest();
        PlatformResponse<FlowDoTaskRespDto> ret = null;
        try {
            FlowDoTaskRespDto respDto = testTaskService.createFlow(testTaskFormDto, operatorStart);
            ret = PlatformResponse.successData(respDto);
        } catch (Exception e) {
            logger.error("createFlow！", e);
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
        return ret;
    }


    @PostMapping("/upload/testcase")
    @ApiOperation(value = "测试用例导入", notes = "测试用例导入")
    public PlatformResponse<?> uploadPartStandard(@RequestPart("file") MultipartFile file) throws IOException {
        ReportUploadContext<UploadTestCaseDto, String> context = testTaskService.testCaseUpload(file);
        return context.isCheckPass() ? PlatformResponse.successData(context.getReadRes()) : PlatformResponse.failedMsg(String.join(",", context.getCheckRes()));
    }

    /**
     * 保存节点数据，但是不提交任务
     */
    @PostMapping("/saveFormData")
    @ApiOperation(value = "保存节点数据", notes = "保存节点数据")
    public PlatformResponse<FlowDoTaskRespDto> saveFormData(@RequestBody TestTaskFormDto testTaskFormDto) {
        logger.info("保存节点数据，{}", testTaskFormDto);
        FlowDoTaskRespDto respDto = testTaskService.saveTestTaskAndTestCaseList(testTaskFormDto, requestTool.getAccountFromRequest());
        return PlatformResponse.successData(respDto);
    }


    /**
     * 审核通过
     */
    @PostMapping("/taskAuditPass")
    @ApiOperation(value = "审核通过", notes = "流程审核处理通过")
    public PlatformResponse<FlowDoTaskRespDto> taskAuditPass(@RequestBody TestTaskFormDto testTaskFormDto) {
        logger.info("审核任务，" + testTaskFormDto);

        String operatorStart = requestTool.getAccountFromRequest();
        FlowDoTaskRespDto respDto = testTaskService.taskAuditPass(testTaskFormDto, operatorStart);
        return PlatformResponse.successData(respDto);
    }

    /**
     * 审核驳回
     */
    @PostMapping("/taskAuditReject")
    @ApiOperation(value = "审核驳回，返回上一个节点", notes = "流程审核驳回处理")
    public PlatformResponse<FlowDoTaskRespDto> taskAuditReject(@RequestBody TestTaskFormDto testTaskFormDto) {
        logger.info("驳回，返回上一个节点，" + testTaskFormDto);
        String operatorStart = requestTool.getAccountFromRequest();
       FlowDoTaskRespDto respDto = testTaskService.taskAuditReject(testTaskFormDto);
        return PlatformResponse.successData(respDto);
    }

    /**
     * 根据流程实例ID或者任务ID检索流程
     *
     * @param testTaskFormDto processId 流程ID
     * @param testTaskFormDto taskId 任务ID
     */
    @PostMapping("/findByProcessIdOrTaskId")
    @ApiOperation(value = "根据流程实例ID或者任务ID检索流程", notes = "根据流程实例ID或者任务ID检索流程状态、备注等，如提供流程实例ID则认为只读方式获取数据")
    public PlatformResponse findByProcessIdOrTaskId(@RequestBody TestTaskFormDto testTaskFormDto) {
        logger.info("查询流程内容，" + testTaskFormDto);
        TestTaskFormDto result = testTaskService.getWorkFlowFormByTaskId(testTaskFormDto);
        return PlatformResponse.successData(result);
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载模板文件")
    public void download(HttpServletResponse response) throws UnsupportedEncodingException {
        //强制下载不打开
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        //使用URLEncoder来防止文件名乱码或者读取错误
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("测试用例模板.xlsx", "UTF-8"));
        try (InputStream input = this.getClass().getResourceAsStream("/templates/test_case_template.xlsx")) {
            OutputStream output = response.getOutputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(input);
            workbook.write(output);
            workbook.close();
        } catch (IOException e) {
            logger.error("Error", e);
        }
    }


}
